package com.frogs.ucenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.GoodsEvaluateEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.EvaluateService;

@Service("evaluateService")
public class EvaluateServiceImpl extends GoodsBaseServiceImpl implements EvaluateService {
	private static Logger log = LoggerFactory.getLogger(EvaluateServiceImpl.class);

	/**
	 * 获取用户商品评论，根据时间排序
	 */
	@Override
	public PageList<Map<String,Object>> getEvaluateList(Integer pageNo, Integer pageSize,
			Integer userId) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_EVALUATE_LIST");
		String[] otherParams = {ApiUrlParamEnum.pageNo.getParamName(),pageNo.toString(),
								ApiUrlParamEnum.pageSize.getParamName(),pageSize.toString(),
								ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								ApiUrlParamEnum.sort.getParamName(),String.valueOf(GoodsEvaluateEnum.SORT_CREATE_TIME.getId()),
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(jsonObjectResult.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			
			JSONArray listJSONArray = jsonObjectResult.getJSONObject("response").getJSONArray("list");
			List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
			if (listJSONArray != null && listJSONArray.size() > 0) {
				Map<Integer, JSONObject> goodsMap = super.getGoodsMap(listJSONArray);
				list = super.mergeGoods(listJSONArray, goodsMap);
			}
	    	result.addAll(list);
	    	
	    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
	    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
	    	
		} catch (IllegalStateException e) {
			log.error("func[getEvaluateList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取用户商品评论接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject updateEvaluate(Integer userId, Integer goodsId ,String content) throws Exception {

		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_EVALUATE_MERGE");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
				ApiUrlParamEnum.goodsId.getParamName(),goodsId.toString(),
				ApiUrlParamEnum.content.getParamName() , content,
				ApiUrlParamEnum.originalGoodsId.getParamName(), "1",
				};
		
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[updateEvaluate] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("修改用户商品评论接口异常！");
		}
		
		return result;
	}

	@Override
	public JSONObject deleteEvaluate(Integer userId,Integer goodsId, Integer evaluationId) throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_EVALUATE_DELETE");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
				ApiUrlParamEnum.goodsId.getParamName(),goodsId.toString(),
				ApiUrlParamEnum.goodsEvaluateId.getParamName(),evaluationId.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[deleteFavorite] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("删除用户商品评论接口异常！");
		}
		
		return result;
	}
}
